import torchvision
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
from torch.utils.data import DataLoader
#loss和反向传播
dataset = torchvision.datasets.CIFAR10("./dataset",train=False,transform=torchvision.transforms.ToTensor(),download=True)
dataloader = DataLoader(dataset,batch_size=1)


class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.model1 = Sequential(
            Conv2d(3, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 64, 5, padding=2),
            MaxPool2d(2),
            Flatten(),
            Linear(1024, 64),
            Linear(64, 10)
        )

    def forward(self,x):
        x = self.model1(x)
        return x


loss = nn.CrossEntropyLoss()
mymodule = MyModule()
for data in dataloader:
    imgs,targets = data
    outputs = mymodule(imgs)
    # print(outputs)
    # print(targets)
    result_loss = loss(outputs,targets)
    #反向传播，用于调整参数，比如卷积网络中的卷积核中的参数，给每个卷积核的参数设置一个grad（梯度），
    # 在进行反向传播的时候，每个节点或者是参数都会求出一个对应的梯度，在优化的过程中优化器就可以根据这个梯度对参数进行优化，
    # 以达到loss降低的目的。比如梯度下降算法
    result_loss.backward()
    print(result_loss)
    print("ok")